<template>
  <el-card class="directory-card">
    <!-- 动态显示目录标题 -->
    <h4>目录：第 {{ startChapter }} 章 - 第 {{ endChapter }} 章</h4>

    <!-- 章节展示区域 -->
    <el-row>
      <el-col :span="8" v-for="(chunk, index) in chunkedData" :key="index">
        <ul class="chapter-list">
          <li v-for="item in chunk" :key="item.id">
            <a href="#" class="chapter-link" @click.prevent="handleClickChapter(item)">
              第{{ item.orderIndex }}章 {{ellipsis( item.title,10) || '无标题' }}
            </a>
          </li>
        </ul>
      </el-col>
    </el-row>

    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        v-model:currentPage="pagination.page"
        :page-size="pagination.size"
        :total="pagination.totalRecords"
        @current-change="handlePageChange"
        layout="total, prev, pager, next"
        background
      />
    </div>
  </el-card>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue';
import axios from 'axios';
import router from '@/router';
import {ellipsis} from '@/utils/util';
import { defineProps } from 'vue'
  const props = defineProps<{
  bookId: Object;  // 使用 ProductItem 作为 item 的类型
}>();

// 定义数据接口结构
interface DirectoryItem {
  id: number;
  title: string;
  orderIndex: number;
}

interface ApiResponse {
  data: {
    listData: DirectoryItem[];
    page: number;
    size: number;
    totalPages: number;
    totalRecords: number;
  };
  code: number;
  msg: string;
}

// 存储目录数据
const directoryData = ref<DirectoryItem[]>([]);

// 分页控制数据
const pagination = ref({
  page: 1,
  size: 10,
  totalRecords: 0,
});

// 分组后的数据，用于列布局
const chunkedData = computed(() => {
  const chunkSize = Math.ceil(directoryData.value.length / 3); // 按3列分组

  
  return Array.from({ length: 3 }, (_, i) =>
    directoryData.value.slice(i * chunkSize, (i + 1) * chunkSize)
  );
});

// 计算当前目录的起始章节
const startChapter = computed(() => {
  return (pagination.value.page - 1) * pagination.value.size + 1;
});

// 计算当前目录的结束章节
const endChapter = computed(() => {
  const end = pagination.value.page * pagination.value.size;
  return Math.min(end, pagination.value.totalRecords); // 取最小值，避免超过总记录数
});

// 获取数据的函数
const fetchDirectoryData = async (page = 1) => {
  try {
    const response = await axios.get<ApiResponse>('/api/chapters/summaries/'+props.bookId, {
      params: {
        pageNum: page,
        pageSize: pagination.value.size, // 使用当前页面大小
      },
    });

    if (response.data.code === 200) {
      const { listData, totalRecords } = response.data.data;
      directoryData.value = listData;
      pagination.value.totalRecords = totalRecords; // 更新总记录数
    }
  } catch (error) {
    console.error('Error fetching directory data:', error);
  }
};

// 页码变化时处理函数
const handlePageChange = (newPage: number) => {
  pagination.value.page = newPage;
  fetchDirectoryData(newPage); // 重新获取新页面数据
};

const handleClickChapter = (item: DirectoryItem) => {
  router.push({ path: '/chapter_read/' + item.id });
};

// 在组件挂载时获取第一页的数据
onMounted(() => {
  fetchDirectoryData();
});
</script>

<style scoped>
.directory-card {
  padding: 10px;
}

h2 {
  margin-bottom: 10px;
  font-size: 18px;
}

.chapter-list {
  list-style: none;
  padding: 0;
}

.chapter-list li {
  width: calc(100% / 3)+1px;
  line-height: 1.8;
  font-size: 14px;
}

.chapter-link {
  color:  var(--bTextColor);
  text-decoration: none;
  cursor: pointer;
  transition: color 0.3s ease, text-decoration 0.3s ease; /* 添加颜色和平滑过渡效果 */
}

.chapter-link:hover {
  color: #3498db; /* 悬停时改变颜色 */
  text-decoration: underline; /* 悬停时显示下划线 */
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}

.chapter-link::after {
  content: '';
  display: block;
  width: 0;
  height: 2px;
  background: #3498db;
  transition: width 0.3s ease;
}

.chapter-link:hover::after {
  width: 100%; /* 悬停时扩展下划线 */
}
</style>
